package cn.org.xwb.bookmall.model.service.impl;

import cn.org.xwb.bookmall.model.po.Address;
import cn.org.xwb.bookmall.model.mapper.AddressMapper;
import cn.org.xwb.bookmall.model.service.IAddressService;
import cn.org.xwb.bookmall.model.utils.BookRedisUtil;
import cn.org.xwb.common.redis.utils.RedisUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xwb
 * @since 2023-12-06
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {
    @Autowired
    private BookRedisUtil bookRedisUtil;

    @Autowired
    private RedisUtil redisUtil;

    private String getKeyAddress(Long userId) {
        return bookRedisUtil.getRedisKeyUser("address:%s", userId.toString());
    }

    public List<Address> findAndCacheAll(Long userId) {
        List<Address> addresses = baseMapper.selectAllByUserId(userId);
        if (Objects.isNull(addresses)) return null;
        Boolean res = redisUtil.setList(getKeyAddress(userId), addresses);
        if (!res) return null;
        return addresses;
    }

    public List<Address> findFromCache(Long userId) {
        List<Address> addresses = (List<Address>) redisUtil.get(getKeyAddress(userId));
        if (Objects.isNull(addresses)) addresses = findAndCacheAll(userId);
        return addresses;
    }
}
